# 导入
import time
import re
from wxauto import WeChat
from urllib.parse import urlparse, parse_qs
import requests
from urllib.parse import urlencode, urlunparse

# 群名列表 逗号分割，群面有表情的 先修改备注
listen_list = [
  '羊毛'
]
# cookie列表  前面自定义名字，后面对应的cookie
cookies = {
    '账号6700':'shshshfpa=ba4a5cff-eaae-21bf-0c7c-3204a0a723c1-1716537011; shshshfpx=ba4a5cff-eaae-21bf-0c7c-3204a0a723c1-1716537011; pinId=15maKJIfAtMqVfMVvcn4JbV9-x-f3wj7; b_webp=1; b_avif=1; jcap_dvzw_fp=Khs-rh57Juj09P_kN17MfAXDQ548_ebbLL-lHZ6DIjGWqIXsmDpAQeb12ZBAaR8MGXDe8byjY9czDJjjxwHxmA==; whwswswws=; __jdu=1729182618002495376843; TrackID=1LYgmrSiYllBaQzQXqfjNUdrJSLiOCqkPLK8Q00QrRGuZX-kD3Qn8NRiqer6_cgvMjeaSQnDOrr4T6mu0nRBbIavNAaA75SkzthuCulF9u-s; light_key=AASBKE7rOxgWQziEhC_QY6yauJpRD9jEVJ2QRQSKAUHgfYnIyZsZCuFiJOTRW8Ru7ZwfsdWL; pin=jd_49735ef72e5a6; unick=loveljlj; 3AB9D23F7A4B3C9B=7HNEOYA6H3PGDBZZAYROLVMF3HCAPBGZTP4YI4TLJQLOJWX6F5D5AM5O3CEND563TXA2NM3Z7N7HJLJDOD57M4SPLI; unpl=JF8EAMhnNSttUR9XBhsBEhUYSl4DWw0BHB9WPGdRAQ9QQlNQGVcSEEB7XlVdWRRKFx9uYRRUVVNOVg4bAisSEXteXVdZDEsWC2tXVgQFDQ8VXURJQlZAFDNVCV9dSRZRZjJWBFtdT1xWSAYYRRMfDlAKDlhCR1FpMjVkXlh7VAQrAh0RGEtUV1ldAUoWAGpvAVZbX0JRBysDKxUge21QWVkKTx8zblcEZB8MF1wGEgAaEF1LW1dWXQFIEANmZgRXWFBPVgMcCx4QIEptVw; __jda=76161171.1729182618002495376843.1729182618.1732624770.1736250191.10; __jdc=76161171; areaId=4; ipLoc-djd=4-48205-0-0; flash=3_SoQMQB6wO6TdnlokfmenspT79FAG_8kzad3bFpTl2jftJthcJhgF1ZP63dSkZ8hT3ovuDg7gELF7-gqVvx4DbOjS_ummUxpMYiT25070W2yhuSnwMh0MabQkJrKDLpMrXCuznXeXvbJ1a6zQNo9s7_mIWu9EAam08nNmnIsWGV_QJFieAaS0dk**; PCSYCityID=CN_500000_500100_0; umc_count=1; shshshfpb=BApXSdxibQ_FAvPLvGOnPC761W3MbYZIbBlQSdz5u9xJ1MlwFDIG2; __jdv=76161171|baidu-pinzhuan|t_288551095_baidupinzhuan|cpc|0f3d30c8dba7459bb52f2eb5eba8ac7d_0_8e221286902f4a8f9db1edc986d3d83a|1736250320003; wxa_level=1; retina=1; cid=9; wqmnx1=MDEyNjM5MnRkbzA7b19hQWkxLGNpTUVyM2ZmNVlJRlI%3D; jxsid=17362503206756131309; appCode=ms0ca95114; webp=1; __jdb=76161171.3.1729182618002495376843|10.1736250191; mba_muid=1729182618002495376843; visitkey=5089397159637537114; mba_sid=17362503207237067633265878506.1; __jd_ref_cls=MDownLoadFloat_ApiDownloadAppPlugInOpenApp; cd_eid=jdd037HNEOYA6H3PGDBZZAYROLVMF3HCAPBGZTP4YI4TLJQLOJWX6F5D5AM5O3CEND563TXA2NM3Z7N7HJLJDOD57M4SPLIAAAAMUICJXDLYAAAAADYVRHRD6OL2XNUX; 3AB9D23F7A4B3CSS=jdd037HNEOYA6H3PGDBZZAYROLVMF3HCAPBGZTP4YI4TLJQLOJWX6F5D5AM5O3CEND563TXA2NM3Z7N7HJLJDOD57M4SPLIAAAAMUICKWUTYAAAAAD7XOCX657KP27IX; _gia_d=1',
}


# 获取微信窗口对象
wx = WeChat()
# 输出 > 初始化成功，获取到已登录窗口：xxxx

# 分割中文和url
def formaturlTokey(text):
    """
        从给定文本中提取描述和URL，并返回一个包含描述-链接对的列表。

        参数:
        text (str): 包含描述和URL的原始文本。

        返回:
        list: 包含元组（描述, URL）的列表。
        """
    # 正则表达式模式，用于查找所有以http或https开头的URL
    url_pattern = re.compile(r'https?://c[^\s]+')

    # 查找所有URL
    urls = url_pattern.findall(text)

    # 初始化一个列表来保存描述-链接对
    description_url_pairs = []

    # 遍历找到的所有URL
    start = 0
    for url in urls:
        # 找到当前URL在原始文本中的位置
        index = text.find(url, start)
        # 提取从上一个结束位置到当前URL开始位置之间的描述
        description = text[start:index].strip()
        # 添加描述-链接对到列表
        description_url_pairs.append((description, url))
        # 更新起始位置为当前URL结束位置之后
        start = index + len(url)

    # 如果最后一个URL之后还有剩余的文本，作为最后一个描述添加
    # if start < len(text):
    #     description_url_pairs.append((text[start:].strip(), ''))

    print(description_url_pairs)
    return description_url_pairs

# 获取url中的 key和id
def getkey(url):
    parsed_url = urlparse(url)
    query_params = parse_qs(parsed_url.query)
    key = query_params.get('key', [None])[0]  # 使用get方法并提供默认值以避免KeyError

    print(key)
    if key == None:
        linkKey = query_params.get('linkKey', [None])[0]
        print(linkKey)
        return ['linkkey',linkKey,'']
    else:
        role_id = query_params.get('roleId', [None])[0]
        return ['key', key, role_id]

def find_jdd_string(text):
    pattern = re.compile(r'=\b(jdd[^;]+)')

    # 查找匹配
    match = pattern.search(text)

    if match:
        return match.group(1)
    else:
        return None

# 领取
def getquan(ck,islinkKey,key, roleid):
    headers = {
        "accept": "application/json",
        "accept-encoding": "gzip, deflate, br, zstd",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
        "cache-control": "no-cache",
        "cookie":ck,
        "origin": "https://coupon.m.jd.com",
        "pragma": "no-cache",
        "priority": "u=1, i",
        "referer": "https://coupon.m.jd.com/",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-site",

        "user-agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1"
    }

    xapitoken = find_jdd_string(ck)
    body = {}
    if islinkKey == 'linkkey':
        body = {"key": '', "roleId": '', "linkKey": key, "to": "m.jd.com","venderid": ""}
    else:
        body = {"key": key, "roleId": roleid, "linkKey": "", "to": "m.jd.com","venderid": ""}
    print('本次请求体:::',body)
    params = {
        "appid": "h5_awake_wxapp",
        "functionId": "mcoupon_getcoupon",
        "client": "wh5",
        "t": int(time.time() * 1000),
        "body":body,
        "_stk": "appid, body, client, functionId, t",
        "_ste": 1,
        "x-api-eid-token": xapitoken,
        "_": int(time.time() * 1000),
        "sceneval": 2,
        "g_login_type": 1,
        "appCode": "ms0ca95114",
        "g_ty": "ajax"
    }
    # 将 body 参数转换为 JSON 字符串
    # 编码参数
    query_string = urlencode(params)

    # 构建完整的 URL
    base_url = "https://api.m.jd.com/client.action"
    full_url = f"{base_url}?{query_string}"

    # 发送请求
    response = requests.get(full_url, headers=headers)
    # 返回响应内容
    try:
        res = response.json()
    except:
        res = 'cookie错误'
    return res



for i in listen_list:
    wx.AddListenChat(who=i, savepic=False)

# 持续监听消息，并且收到消息后回复“收到”
wait = 0.2  # 设置1秒查看一次是否有新消息

time.sleep(10) #就是这里，等一会，大家自己试一下，估计再少一些也没问题
while True:

    msgs = wx.GetListenMessage()
    for chat in msgs:
        who = chat.who  # 获取聊天窗口名（人或群名）
        one_msgs = msgs.get(chat)  # 获取消息内容
        # 回复收到
        for msg in one_msgs:
            msgtype = msg.type  # 获取消息类型
            sender = msg.sender # 发送消息者
            content = msg.content  # 获取消息内容，字符串类型的消息内容
            print(f'【{who}】：{sender}:{content}')
            # ===================================================
            # 处理消息逻辑（如果有）
            #
            # 处理消息内容的逻辑每个人都不同，按自己想法写就好了，这里不写了
            #
            # ===================================================

            # 如果是好友发来的消息（即非系统消息等），则回复收到
            if msgtype == 'friend':
                # 判断不同的优惠券 用不同的方式
                if 'coupon.m.jd.com/' in content:
                    print('检测到优惠券')
                    # 分割名字和url
                    objresult = formaturlTokey(content)
                    for desc, url in objresult:
                        # 提取url中的key和id
                        # parsed_url = urlparse(obj.url)
                        print(desc, url)
                        keys = getkey(url)

                        print(keys[0], keys[1], keys[2])

                        # 领取券
                        for key, value in cookies.items():
                            print('本次请求用户:',key)
                            res = getquan(cookies[key], keys[0], keys[1], keys[2])
                            # print(res['data'])
                            try:
                                if res['data']['resultCode'] == 999:
                                    print(
                                        '账号:' + key + ' 领取成功 该券满' + str(res["data"]["quota"]) + '-' + str(
                                            res["data"]["discount"]))


                            except Exception as e:
                                # print(f"An error occurred: {e}")
                                # 无论是否有错误发生，这里的代码都会被执行
                                print("可惜~发生错误了~")
                            finally:
                                print("-----------------------------------")
                                print(res)
                            time.sleep(1)

                # chat.SendMsg('收到')  # 回复收到
    time.sleep(wait)